<template>
  <div class="table-box">
    <pro-table ref="proTableRef" row-key="id" :columns="columns" :request-api="getFilePageApi">
      <!-- 状态 -->
      <template #isEnable="scope">
        <el-switch
          v-model="scope.row.isEnable"
          :loading="scope.row.loading"
          active-text="已启用"
          inactive-text="已禁用"
          inline-prompt
          :before-change="handleEnable.bind(scope, scope.row)"
        />
      </template>
      <!-- 菜单操作 -->
      <template #operation="{ row }">
        <el-button v-auth="'sys:file:down'" type="primary" link :icon="View" @click="handleSearch(row)"> 查看 </el-button>
        <el-button v-auth="'sys:file:del'" type="danger" link :icon="Delete" @click="handleDelete(row)"> 删除 </el-button>
      </template>
    </pro-table>

    <!-- 图片预览 -->
    <el-image-viewer v-if="preview" :url-list="imageViewUrlList" hide-on-click-modal @close="preview = false" />
  </div>
</template>

<script setup lang="ts" name="fileManage">
import type { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import type { SysFile } from "@/api/interface";
import { ref } from "vue";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { statusConst, fileCategoryConst } from "@/utils/dict";
import { ElMessageBox } from "element-plus";
import { View, Delete } from "@element-plus/icons-vue";
import { CANROCNET } from "@/api/config/servicePort";
import { switchEnableFileApi, deleteFileApi, getFilePageApi, downloadFileApi } from "@/api/modules/system/file";
import ProTable from "@/components/ProTable/index.vue";

/** 表格实例 */
const proTableRef = ref<ProTableInstance>();

/** 图片预览 */
const preview = ref(false);
/** 图片预览地址 */
const imageViewUrlList = ref<string[]>([]);
/** 表格配置项 */
const columns: ColumnProps[] = [
  { prop: "name", label: "文件名称", align: "left", width: 200, search: { el: "input" } },
  { prop: "url", label: "预览地址", align: "left" },
  { prop: "size", label: "文件大小(K)", width: 120 },
  { prop: "category", label: "类目", width: 100, enum: fileCategoryConst },
  { prop: "createUserName", label: "上传用户", width: 140 },
  { prop: "isEnable", label: "状态", width: 100, enum: statusConst },
  { prop: "operation", label: "操作", width: 180, fixed: "right" },
  {
    prop: "createTime",
    label: "上传时间",
    width: 180,
    isShow: false,
    search: {
      el: "date-picker",
      key: "date",
      props: {
        type: "daterange",
        valueFormat: "YYYY-MM-DD"
      }
    }
  }
];

/**
 * 启用/禁用文件
 *
 * @param param 选中的文件
 * @returns void
 */
const handleEnable = (param: Partial<SysFile.Result> & { loading?: boolean }) => {
  param.loading = true;
  return switchEnableFileApi({ id: param.id! })
    .then(({ data }) => {
      if (data) {
        return Promise.resolve(true);
      } else return Promise.reject(new Error("修改状态失败"));
    })
    .finally(() => {
      param.loading = false;
    });
};

/**
 * 删除文件
 *
 * @param param 选中的文件
 * @returns void
 */
const handleDelete = (param: Partial<SysFile.Result>) => {
  useHandleData(deleteFileApi, { ids: [param.id] }, `删除【${param.name}】文件`).then(res => {
    if (res) proTableRef.value?.getTableList();
  });
};

/**
 * 查看文件
 *
 * @param param 选中的文件
 * @returns void
 */
const handleSearch = (param: Partial<SysFile.Result>) => {
  const extendsArr = [".jpg", ".png", ".jpeg", ".gif"];
  if (param.extend && extendsArr.includes(param.extend)) {
    preview.value = true;
    imageViewUrlList.value = [CANROCNET + param.url!];
  } else {
    ElMessageBox.confirm("文件不是图片格式，无法预览。是否下载？", "提示", { type: "warning" })
      .then(() => {
        // 去除文件后缀名
        useDownload(downloadFileApi, "", { id: param.id! }, true);
      })
      .catch(() => {
        return;
      });
  }
};
</script>
